<script setup lang='ts'>
import { computed, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCart } from '@/composables/useCart'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'
import { createOrder } from '@/api/order'
import { addOrderGoods } from '@/api/orderGoods'

const router = useRouter()
const auth = useAuthStore()
const { items, totalPrice, clearCart } = useCart()

const linkUser = ref('')
const linkPhone = ref('')
const linkAddress = ref('')

onMounted(() => {
  if (!auth.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/')
  }
})

const total = computed(() => Number(totalPrice.value.toFixed(2)))
const submitting = ref(false)

async function submitOrder() {
  if (!items.value.length) {
    ElMessage.warning('购物车为空')
    return
  }
  if (!linkUser.value || !linkPhone.value || !linkAddress.value) {
    ElMessage.warning('请填写收货信息')
    return
  }

  submitting.value = true
  try {
    const orderRes = await createOrder({
      totalPrice: total.value,
      linkUser: linkUser.value,
      linkPhone: linkPhone.value,
      linkAddress: linkAddress.value,
      state: 'CREATED',
    })
    const orderId = orderRes?.data?.data?.id
    if (!orderId) {
      throw new Error('下单失败')
    }
    // 创建订单明细
    for (const it of items.value) {
      await addOrderGoods({ orderId, goodId: Number(it.product.id), count: it.quantity })
    }
    await clearCart()
    ElMessage.success('下单成功')
    router.push('/client/MyOrders')
  } catch (e:any) {
    ElMessage.error(e?.message || '下单失败')
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <div class="order-confirm">
    <el-card>
      <template #header>
        <div class="hd">确认订单</div>
      </template>
      <div class="addr">
        <el-form label-width="80px" style="max-width: 560px">
          <el-form-item label="收货人">
            <el-input v-model="linkUser" placeholder="姓名" />
          </el-form-item>
          <el-form-item label="电话">
            <el-input v-model="linkPhone" placeholder="手机号" />
          </el-form-item>
          <el-form-item label="地址">
            <el-input v-model="linkAddress" placeholder="详细地址" />
          </el-form-item>
        </el-form>
      </div>

      <div class="list">
        <el-table :data="items" border>
          <el-table-column label="商品" min-width="360">
            <template #default="{ row }">
              <div class="row">
                <img :src="row.product.imgs" class="thumb" />
                <div class="meta">
                  <div class="name">{{ row.product.name }}</div>
                  <div class="price">￥{{ row.product.saleMoney }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="120" align="center">
            <template #default="{ row }">{{ row.quantity }}</template>
          </el-table-column>
          <el-table-column label="小计" width="140" align="center">
            <template #default="{ row }">￥{{ Number(row.product.saleMoney) * row.quantity }}</template>
          </el-table-column>
        </el-table>
      </div>

      <div class="footer">
        <div class="total">合计：<b>￥{{ total.toFixed(2) }}</b></div>
        <el-button type="primary" :loading="submitting" @click="submitOrder">提交订单</el-button>
      </div>
    </el-card>
  </div>
}</template>

<style scoped>
.order-confirm{ width: 97.5%; margin: 16px auto; }
.hd{ font-weight: 700; }
.row{ display: flex; align-items: center; gap: 12px; }
.thumb{ width: 64px; height: 64px; object-fit: cover; border-radius: 6px; }
.meta .name{ font-weight: 600; }
.meta .price{ color: #f56c6c; margin-top: 2px; }
.footer{ display: flex; justify-content: flex-end; align-items: center; gap: 12px; padding: 16px 8px; }
.total{ margin-right: auto; }
</style>


